package com.tobeing.voicechat.views;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import com.tobeing.voicechat.R;
import com.tobeing.voicechat.customs.RecorderManager;

/**
 * Created by Administrator on 2017/10/30/030.
 */

public class RecorderButton extends Button implements RecorderManager.RecorderPrepareListener {
    private final int BTN_STATE_NORMAL = 101;
    private final int BTN_STATE_RECORDING = 102;
    private final int BTN_STATE_CANCEL = 103;

    private final int MSG_RECORDER_PREPARED = 101;
    private final int MSG_VOICE_CHANGE = 102;
    private final int MSG_RECORDER_CANCEL = 103;

    private int mCurrentState = BTN_STATE_NORMAL;
    //audio recorder是否prepare完毕
    private boolean mPrepareRecording = false;

    private RecorderDialog mDialog;

    private RecorderManager mRecorderManager;
    //录音时长
    private float mTime = 0;
    //是否出发长按
    private boolean mLongClicked = false;

    private RecorderFinishListener mRecorderFinishListener;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_RECORDER_PREPARED:
                    showRecorderDialog();
                    mPrepareRecording = true;
                    handler.post(runnable);
                    break;
                case MSG_VOICE_CHANGE:
                    if(mDialog != null) {
                        mDialog.setVoiceLevel(mRecorderManager.getVoiceLevel(7));
                    }
                    break;
                case MSG_RECORDER_CANCEL:
                    if(mDialog != null) {
                        closeRecorderDialog();
                    }
                    mRecorderManager.cancelRecorder();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(mPrepareRecording) {
                mTime += 0.1;
                Log.i("time", mTime + "");
                mHandler.sendEmptyMessage(MSG_VOICE_CHANGE);
                handler.postDelayed(runnable, 100);
            }
        }
    };

    public RecorderButton(Context context) {
        this(context, null);
    }

    public RecorderButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecorderButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mRecorderManager = RecorderManager.getInstance(Environment.getExternalStorageDirectory() + "/voicechat_recorder");
        mRecorderManager.setRecorderPrepareListener(this);

        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mLongClicked = true;
                mRecorderManager.prepareRecorder();
                return false;
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                changeState(BTN_STATE_RECORDING);
                break;
            case MotionEvent.ACTION_MOVE:
                if(mPrepareRecording) {
                    if (cancelRecorder(event.getX(), event.getY())) {
                        changeState(BTN_STATE_CANCEL);
                    } else {
                        changeState(BTN_STATE_RECORDING);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if(!mLongClicked){
                    reset();
                }else if(!mPrepareRecording || mTime < 1){
                    if(mDialog != null) {
                        mDialog.tooShort();
                    }
                    mHandler.sendEmptyMessageDelayed(MSG_RECORDER_CANCEL,2000);
                }else if(mCurrentState == BTN_STATE_RECORDING){
                    mRecorderManager.releaseRecorder();
                    closeRecorderDialog();
                    if(mRecorderFinishListener != null){
                        mRecorderFinishListener.finished(mRecorderManager.getCurrentPath(), mTime);
                    }
                }else if(mCurrentState == BTN_STATE_CANCEL){
                    mHandler.sendEmptyMessage(MSG_RECORDER_CANCEL);
                }
                reset();
                break;
        }
        return super.onTouchEvent(event);
    }

    public void setRecorderFinishListener(RecorderFinishListener listener){
        mRecorderFinishListener = listener;
    }

    private boolean cancelRecorder(float x, float y) {
        if (x > getWidth() || x < 0) {
            return true;
        } else if (y > getHeight() + 100 || y < -100) {
            return true;
        }
        return false;
    }

    private void changeState(int state) {
        if (mCurrentState != state) {
            mCurrentState = state;
            switch (state) {
                case BTN_STATE_NORMAL:
                    setText("按住说话");
                    setBackgroundResource(R.drawable.btn_normal);
                    break;
                case BTN_STATE_RECORDING:
                    setText("松开发送");
                    setBackgroundResource(R.drawable.btn_pressed);
                    if(mPrepareRecording && mDialog != null) {
                        mDialog.recording();
                    }
                    break;
                case BTN_STATE_CANCEL:
                    setText("松开取消");
                    setBackgroundResource(R.drawable.btn_pressed);
                    if(mDialog != null) {
                        mDialog.cancelRecorder();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void reset(){
        mLongClicked = false;
        mPrepareRecording = false;
        mTime = 0;
        changeState(BTN_STATE_NORMAL);
    }

    private void showRecorderDialog(){
        if(mDialog == null){
            mDialog = new RecorderDialog(getContext());
        }
        if(!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    private void closeRecorderDialog(){
        if(mDialog != null){
            mDialog.dismiss();
            mDialog = null;
        }
    }

    @Override
    public void prepared() {
        mHandler.sendEmptyMessage(MSG_RECORDER_PREPARED);
    }

    public interface RecorderFinishListener{
        void finished(String path, float time);
    }
}
